package aplicacao.atender.chamadas;
import java.telephony.*;
import java.telephony.events.*;
import java.telephony.media.*;
import java.telephony.media.events.*;


class MachineCallObserver implements MediaCallObserver {

  /*
   * This CallObserver will be notified of Call events. We want to first
   * answer the incoming telephone call, and then perform the neccessary
   * media actions for the answering machine.
   */
  public void callChangedEvent(CallEv evlist[]) {

    for (int i = 0; i < evlist.length; i++) {
      CallEv ev = evlist[i];

      /*
       * When the TerminalConnection associated with the local Terminal is
       * create we want to set it up for source and destinations of the
       * voice media.
       */
      if (ev instanceof TermConnCreatedEv) {

        TerminalConnection tc = ((TermConnEv)ev).getTerminalConnection();
        MediaTerminalConnection mtc = (MediaTerminalConnection)tc;

        try {
          mtc.usePlayURL(new URL("file:/audio/prompt.au"));
          mtc.useRecordURL(new URL("file:/audio/message1.au"));
        } catch (Exception excp) {
          // Handle exceptions
        }
      }
      else if (ev instanceof TermConnRingingEv) {
        /*
        * We want to answer the telephone.
        */
        TerminalConnection tc = ((TermConnEv)ev).getTerminalConnection();
        try {
          tc.answer();
        } catch (Exception excp) {
          // Handle Exceptions
        }
      }
      else if (ev instanceof MediaTermConnAvailableEv) {

        /* We want to start playing of the prompt. */
        TerminalConnection tc = (TermConnEv)ev.getTerminalConnection();
        MediaTerminalConnection mtc = (MediaTerminalConnection)tc;

        try {
          mtc.startPlaying();
        } catch (Exception excp) {
          // Handle exceptions
        }
      }
      else if (ev instanceof MediaTermConnStateEv) {

        /* When the playing stops, start the recording of the message. */

        TerminalConnection tc = (TermConnEv)ev.getTerminalConnection();
        MediaTerminalConnection mtc = (MediaTerminalConnection)tc;

        try {
          /* Want to find out when playing is done */
          int state = mtc.getMediaState();

          if (state & MediaTerminalConnection.PLAYING == 0) {
            mtc.startRecording();
          }
        } catch (Exception excp) {
          // Handl exceptions
        }
      }
      else if (ev instance MediaTermConnUnavailableEv) {

        /* When the channel on the telephone line becomes unavailable, then
         * stop all activity.
         */
        TerminalConnection tc = (TermConnEv)ev.getTerminalConnection();
        MediaTerminalConnection mtc = (MediaTerminalConnection)tc;

        try {
          mtc.stopRecording();
          mtc.stopPlaying();
        } catch (Exception excp) {
          // Handle exceptions
        }
      }
    }
  }
}

